package com.chenyue.cm.live.im.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.DomainConfig;
import com.chenyue.cm.live.im.service.ImService;
import com.chenyue.cm.live.im.vo.LiveCron;
import com.chenyue.cm.user.dao.JdAppUserMapper;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.utils.OkHttpUtils;
import com.chenyue.cm.utils.RedisUtils;
import com.chenyue.cm.utils.im.ImBanUserList;
import com.chenyue.cm.utils.im.ImCommonResult;
import com.chenyue.cm.utils.im.util.ImConfig;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * @author libingxing
 */
@Service
public class ImServiceImpl implements ImService {

    private final RedisUtils redisUtils;

    private final JdAppUserMapper userMapper;

    private static final Logger logger = LoggerFactory.getLogger(ImServiceImpl.class);

    public ImServiceImpl(RedisUtils redisUtils, @Qualifier("jdAppUserMapper") JdAppUserMapper userMapper) {
        this.redisUtils = redisUtils;
        this.userMapper = userMapper;
    }

    private String getHeadImg(JdAppUser user) {
        return DomainConfig.LOCALHOST + user.getHeadImg();
    }

    /**
     * 拼接url
     *
     * @param service 服务
     * @param method  方法
     * @return String
     */
    @Override
    public String getUrl(String service, String method) {
        String sign = redisUtils.getImUserSign();
        return "https://console.tim.qq.com" +
                "/v4/" + service + "/" + method + "?" +
                "sdkappid=" + ImConfig.SDK_APP_ID +
                "&identifier=" + ImConfig.IDENTIFY +
                "&usersig=" + sign +
                "&random=" + RandomUtil.getRandom(true).nextInt() * 0xFFFFFFFL +
                "&contenttype=" + ImConfig.CONTENT_TYPE;
    }

    /**
     * 账号导入IM
     *
     * @param user 用户信息
     * @return 结果
     * @throws IOException post
     */
    @Override
    public boolean accountImport(JdAppUser user) throws IOException {
        Map<String, Object> map = new HashMap<>(3);
        map.put("Identifier", user.getId() + "");
        map.put("Nick", user.getUserName());
        map.put("FaceUrl", getHeadImg(user));
        String s = OkHttpUtils.doPostJson(getUrl("im_open_login_svc", "account_import"), JSON.toJSONString(map));
        JSONObject result = JSON.parseObject(s);
        return "0".equalsIgnoreCase(result.get("ErrorCode").toString());
    }

    /**
     * 查询用户详情
     *
     * @param user 用户id
     * @return Success
     * @throws IOException post
     */
    @Override
    public Success<String> viewAccount(JdAppUser user) throws IOException {
        List<HashMap<String, String>> list = new ArrayList<>(1);
        HashMap<String, String> map = new HashMap<>(1);
        map.put("UserID", user.getId() + "");
        list.add(map);
        RequestBody param = new FormBody.Builder()
                .add("CheckItem", list.toString())
                .build();
        String s = OkHttpUtils.doPost(getUrl("im_open_login_svc", "account_check"), param);
        return Success.success(s);
    }

    /**
     * 删除IM用户
     *
     * @param user 用户
     * @throws IOException post
     */
    @Override
    public void deleteAccount(JdAppUser user) throws IOException {
        String url = getUrl("im_open_login_svc", "account_delete");
        Map<String, List<Map<String, Object>>> map = new HashMap<>(1);
        List<Map<String, Object>> list = new ArrayList<>(10);
        Map<String, Object> content = new HashMap<>(1);
        content.put("UserID", user.getId() + "");
        list.add(content);
        map.put("DeleteItem", list);
        String param = JSON.toJSONString(map);
        OkHttpUtils.doPostJson(url, param);
    }

    /**
     * 创建聊天室
     *
     * @param id   用户ID
     * @param name 聊天室名称
     * @param zbId 主播id
     * @return 聊天室房间号
     * @throws IOException post
     */
    @Override
    public String createGroup(Integer id, String name, String zbId) throws IOException {
        Map<String, String> map = new HashMap<>(3);
        map.put("Owner_Account", id + "");
        map.put("Type", "AVChatRoom");
        map.put("Name", name);
        map.put("GroupId", "group_" + zbId);
        String param = JSON.toJSONString(map);
        String s = OkHttpUtils.doPostJson(getUrl("group_open_http_svc", "create_group"), param);
        JSONObject result = JSON.parseObject(s);
        if ("0".equalsIgnoreCase(result.get("ErrorCode").toString())) {
            return result.get("GroupId").toString();
        } else {
            return "";
        }
    }

    /**
     * 解散聊天室
     *
     * @param groupId 聊天室id
     */
    @Override
    public void deleteGroup(String groupId) throws IOException {
        Map<String, String> map = new HashMap<>(1);
        map.put("GroupId", groupId);
        String param = JSON.toJSONString(map);
        OkHttpUtils.doPostJson(getUrl("group_open_http_svc", "destroy_group"), param);
    }

    /**
     * 修改IM用户
     *
     * @param user 用户信息
     * @throws IOException post
     */
    @Override
    public void setProfile(JdAppUser user) throws IOException {
        String url = getUrl("profile", "portrait_set");
        Map<String, String> map = new HashMap<>(1);
        map.put("Tag_Profile_IM_Nick", user.getUserName());
        map.put("Tag_Profile_IM_SelfSignature", user.getSignature());
        map.put("Tag_Profile_IM_Image", user.getHeadImg().contains("http") ? user.getHeadImg() : DomainConfig.LOCALHOST + user.getHeadImg());
        String param = JSON.toJSONString(map);
        OkHttpUtils.doPostJson(url, param);
    }

    /**
     * 发送消息
     *
     * @param userId  用户id
     * @param msgType 1文字2图片
     * @param cron    消息内容
     */
    @Override
    public void sendMsg(int userId, int msgType, LiveCron cron) throws IOException {
        JdAppUser user = userMapper.selectById(userId);
        Map<String, Object> map = new HashMap<>(1);
        map.put("GroupId", "管理员群组");
        map.put("From_Account", userId + "");
        map.put("Random", RandomUtil.getRandom(true).nextInt() * 0xFFFFFFFL + "");
        List<JSONObject> msgList = new ArrayList<>(1);
        JSONObject msg1 = new JSONObject();
        msg1.put("MsgType", "TIMCustomElem");
        JSONObject msgBody = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("code", cron.getId() != null ? cron.getId() : "");
        if (msgType == 1) {
            data.put("content", cron.getContent());
        } else {
            data.put("img", cron.getImage());
            data.put("imageSize", cron.getImageSize());
        }
        data.put("nickname", user.getUserName());

        data.put("avatar", getHeadImg(user));
        data.put("userId", userId);
        data.put("createTime", DateUtil.format(Calendar.getInstance().getTime(), "yyyy.MM.dd HH:mm"));
//        气功直播消息类型说明
//        1：消息（用户文字消息、管理员文字消息、管理员文字带图消息）
//        2：礼物消息（不区分用户、管理员）
//        3：管理员消息（置顶、取消置顶、删除消息）
        if (userId == 2) {
            data.put("type", 1);
        } else {
            data.put("type", 3);
        }
        data.put("isTop", 0);
        msgBody.put("Data", data.toJSONString());
        msg1.put("MsgContent", msgBody);
        msgList.add(msg1);
        map.put("MsgBody", msgList);
        String param = JSON.toJSONString(map);
        String s = OkHttpUtils.doPostJson(getUrl("group_open_http_svc", "send_group_msg"), param);
        logger.error(param);
        logger.error(s);
    }

    /**
     * 获取当前群组的在线人数
     *
     * @return String
     * @throws IOException 传输异常
     */
    @Override
    public String getCurrentGroupMemberNumber(String groupId) throws IOException {
        Map<String, Object> map = new HashMap<>(1);
        map.put("GroupId", groupId);
        String param = JSON.toJSONString(map);
        String s = OkHttpUtils.doPostJson(getUrl("group_open_http_svc", "get_online_member_num"), param);
        JSONObject result = JSON.parseObject(s);
        if ("0".equalsIgnoreCase(result.get("ErrorCode").toString())) {
            return result.get("OnlineMemberNum").toString();
        }
        logger.error(param);
        logger.error(s);
        return null;
    }

    /**
     * 查看该用户是否被禁言
     *
     * @param userId   用户id
     * @param recordId 群组id
     * @return 是否关播
     */
    @Override
    public boolean isBanSendMsg(Integer userId, Integer recordId) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("GroupId", recordId + "");
        String param = JSON.toJSONString(map);
        try {
            String s = OkHttpUtils.doPostJson(getUrl("group_open_http_svc", "get_group_shutted_uin"), param);
            System.err.println(s);
            final ImCommonResult commonResult = JSON.parseObject(s, ImCommonResult.class);
            if (commonResult.getErrorCode() == 0) {
                for (ImBanUserList banUser : commonResult.getShuttedUinList()) {
                    if (banUser.getMember_Account().equals(userId)) {
//                        禁言时间大于当前时间
                        return banUser.getShuttedUntil() > System.currentTimeMillis() / 1000;
                    } else {
                        return false;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
